package com.bj58.mis.apm.client.transfer.impl;

import com.bj58.mis.apm.client.core.ApmLogEntity;
import com.bj58.mis.apm.client.core.AppNodeContext;
import com.bj58.mis.apm.client.core.util.JsonUtil;
import com.bj58.mis.apm.client.transfer.Transfer;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

public class TransferHttpImpl implements Transfer {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void transfer(ApmLogEntity entity) {
        try{
            logger.debug("transfer ApmLogEntity : " + JsonUtil.toJson(entity));
            String url = getLogReceiverUrl();
            String result = httpPost(url, JsonUtil.toJson(entity));
            logger.debug("transfer ApmLogEntity result : " + result);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }
    private String getLogReceiverUrl(){
        String serverUrl = AppNodeContext.getValue("server.http.url");
        if (serverUrl.endsWith("/")){
            serverUrl = serverUrl.substring(0, serverUrl.length()-1);
        }
        return serverUrl + "/log";
    }

    private String httpPost(String url, String body) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setEntity(new StringEntity(body, Charset.forName("UTF-8")));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, "UTF-8");
    }
}
